package org.ahuanlien.crm.service.impl;

import org.ahuanlien.crm.domain.Employee;
import org.ahuanlien.crm.domain.Role;
import org.ahuanlien.crm.mapper.EmployeeMapper;
import org.ahuanlien.crm.query.EmployeeQueryObject;
import org.ahuanlien.crm.service.IEmployeeService;
import org.ahuanlien.crm.util.PageResult;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;

@Service
public class EmployeeServiceImpl implements IEmployeeService {

	@Autowired
	private EmployeeMapper employeeMapper;


	public void saveOrUpdate(Employee record) {
		if (record.getId() != null) {
			employeeMapper.removeRolenRelation(record.getId());
			for (Role role : record.getRoles()) {
				employeeMapper.saveRoleRelation(record.getId(), role.getId());
			}
			employeeMapper.updateByPrimaryKey(record);
		} else {
			//密码加密,(原密码,盐,散列次数)
			Md5Hash md5Hash = new Md5Hash(record.getPassword(), record.getUsername(), 2);
			record.setPassword(md5Hash.toString());
			employeeMapper.insert(record);
			for (Role role : record.getRoles()) {
				employeeMapper.saveRoleRelation(record.getId(), role.getId());
			}
		}
	}

	public PageResult query(EmployeeQueryObject qo) {
		int count = employeeMapper.queryForCount(qo);
		if (count == 0) {
			return new PageResult(count, Collections.EMPTY_LIST);
		}
		List<Employee> result = employeeMapper.queryForList(qo);
		return new PageResult(count, result);
	}

	public Employee getByUsername(String username) {
		Employee employee = employeeMapper.getByUsername(username);
		return employee;
	}

	public void changeState(Long id) {
		employeeMapper.changeState(id);
	}

	public void initPassword(Long id) {
		employeeMapper.initPassword(id);
	}

	public List<Employee> selectAll() {
		return employeeMapper.selectAll();
	}

}
